<?php
class MyDbCriteria extends CDbCriteria {
	
	const JOIN_INNER = 'JOIN';
	const JOIN_LEFT = 'LEFT JOIN';
	const JOIN_RIGHT = 'RIGHT JOIN';
	
	protected $_conditions = array();

	protected $_joins = array();
	
	public function addAndCondition($condition,$key=null) {
		$data = array(
			'condition' => $condition,
			'operator' => 'AND'
		);
		
		if ($key) {
			$this->_conditions[$key] = $data;
		} else {
			$this->_conditions[] = $data;
		}
		
		return parent::addCondition($condition);
	}
	
	public function removeCondition($key) {
		unset($this->_conditions[$key]);
		
		$this->condition = '';
		foreach($this->_conditions as $data) {
			$this->condition = $this->condition=='' ? 
				$data['condition'] :
				'('.$this->condition.') '.$data['operator'].' ('.$data['condition'].')';
		}
	}
	
	public function addJoin($table, $condition, $type='JOIN', $alias=null) {
		$this->_joins[$table] = array(
			'table' => $table,
			'condition' => $condition,
			'type' => $type,
			'alias' => $alias
		);
		$this->_updateJoinData();
	}

	public function removeJoin($table) {
		unset($this->_joins[$table]);
		$this->_updateJoinData();
	}
	
	protected function _updateJoinData() {
		$this->join = '';
		foreach($this->_joins as $data) {
			$this->join .= ' '.$data['type'].' '.$data['table'];
			if (isset($data['alias']))
				$this->join .= ' AS '.$data['alias'];
			$this->join .= ' ON '.$data['condition'];
		}
	}
	
	public function getCommand() {
		$cmd = Yii::app()->db->createCommand();
		$cmd->select = $this->select;
		$cmd->join = $this->join;
		$cmd->where = $this->condition;
		$cmd->group = $this->group;
		$cmd->params = $this->params;
		return $cmd;
	}
}